package com.onelap.bls.tc2.ui.index;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothProfile;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ServiceUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bls.blslib.base.BaseActivity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.onelap.bls.tc2.R;
import com.onelap.bls.tc2.ble.BleCallback;
import com.onelap.bls.tc2.ble.BleParams;
import com.onelap.bls.tc2.ble.BleService;
import com.onelap.bls.tc2.ble.BleUtil;
import com.onelap.bls.tc2.ui.calibration.CalibrationActivity;
import com.onelap.bls.tc2.util.HandleUtils;
import com.onelap.bls.tc2.view.TitleBar;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@SuppressLint("SetTextI18n")
public class IndexActivity extends BaseActivity {
    @BindView(R.id.tb_title_bar)
    TitleBar tbTitleBar;
    @BindView(R.id.rv_device_list)
    RecyclerView rvDeviceList;
    @BindView(R.id.btn_search)
    Button btnSearch;
    @BindView(R.id.btn_connect)
    Button btnConnect;
    @BindView(R.id.btn_1)
    Button btnSend1;
    @BindView(R.id.btn_2)
    Button btnSend2;

    private BleUtil bleUtil;
    private DeviceListAdapter deviceListAdapter;

    private List<DeviceBean> bluetoothDeviceList = new ArrayList<>();
    private DeviceBean selectedDeviceBean = null;//默认选中的设备
    private int selectedDeviceBeanIndex = -1; //默认选中的设备位置

    @Override
    protected void initParams() {
        super.initParams();
        bleUtil = new BleUtil(getActivity(), bleCallback);
        bleUtil.bindBleService();
        bleUtil.applyForPermission(false);
        deviceListAdapter = new DeviceListAdapter(bluetoothDeviceList);
    }

    @Override
    protected int initLayoutId() {
        return R.layout.activity_index;
    }

    @Override
    protected void initFvb() {
        super.initFvb();
        ButterKnife.bind(this);
    }

    @Override
    protected void initTitle() {
        super.initTitle();
        final TitleBar titleBar = findViewById(R.id.tb_title_bar);
        titleBar.setTitle("设备选择");
        titleBar.setBackgroundColor(Color.BLACK);
        titleBar.setTitleColor(Color.WHITE);
        titleBar.setCenterClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (bleUtil.getBleService().getBluetoothGatt() != null) {
                    bleUtil.getBleService().closeDeviceBluetooth();
                    myHandler.sendMessage(Message.obtain(myHandler, 4));
                }
            }
        });
    }

    @Override
    protected void initView() {
        super.initView();
        rvDeviceList.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvDeviceList.setAdapter(deviceListAdapter);
        deviceListAdapter.bindToRecyclerView(rvDeviceList);
        deviceListAdapter.setEmptyView(R.layout.view_empty_list);
    }

    @Override
    protected void initListener() {
        super.initListener();
        deviceListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                bleUtil.bleScanDevice(false);
                if (selectedDeviceBeanIndex != -1)
                    bluetoothDeviceList.get(selectedDeviceBeanIndex).setSelect(false);
                bluetoothDeviceList.get(position).setSelect(true);
                selectedDeviceBeanIndex = position;
                selectedDeviceBean = bluetoothDeviceList.get(position);
                deviceListAdapter.notifyDataSetChanged();
            }
        });
    }

    @OnClick(R.id.btn_search)
    public void onBtnSearchClicked() {
        bleUtil.checkBluetoothIsAvailable();
    }

    @OnClick(R.id.btn_connect)
    public void onBtnConnectClicked() {
        bleUtil.bleScanDevice(false);
        progressDialog.show();
        if (bleUtil == null) {
            return;
        }
        if (selectedDeviceBean.getDevice() == null) {
            return;
        }
        if (bleUtil.getBleService() == null) {
            return;
        }
        bleUtil.getBleService().connectionDeviceBluetooth(selectedDeviceBean.getDevice());
    }

    @OnClick(R.id.btn_1)
    public void onBtnSend1Clicked(){
        try {
            bleUtil.writeRXCharacteristicUTF_8("4B28006400");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @OnClick(R.id.btn_2)
    public void onBtnSend2Clicked() {
        try {
            bleUtil.writeRXCharacteristicUTF_8("4B90016400");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == BleParams.Code.REQUEST_CODE_INTENT_ENABLE_BLUETOOTH)
            switch (resultCode) {
                case Activity.RESULT_OK:
                    bleCallback.bleBluetoothEnableState(true, true);
                    break;
                case Activity.RESULT_CANCELED:
                    bleCallback.bleBluetoothEnableState(true, false);
                    break;
            }
    }

    @Override
    protected void initResume() {
        super.initResume();
        bleUtil = new BleUtil(getActivity(), bleCallback);
        bleUtil.bindBleService();
    }

    private BleCallback bleCallback = new BleCallback() {

        @Override
        public void bleHaveBlePermission(boolean isDoNext) {
            LogUtils.i("HaveBlePermission", "HaveBlePermission");
        }

        @Override
        public void bleBluetoothEnableState(boolean isSupport, boolean isEnable) {
            if (!isSupport) {
                if (!isResume)
                    ToastUtils.showShort("蓝牙未开启或设备不支持蓝牙");
            } else if (!isEnable) {
                LogUtils.i("蓝牙未开启");
            } else {
                bleUtil.bleScanDevice(bleUtil.scanDeviceStateCode != BleParams.ScanDeviceStateCode.SCAN_ING);
            }
        }

        @Override
        public void bleServiceConnected(ComponentName componentName, IBinder iBinder) {
            LogUtils.i("ServiceConnected", componentName.toString());
        }

        @Override
        public void bleServiceDisConnected(ComponentName componentName) {
            LogUtils.i("ServiceDisConnected", componentName.toString());
        }

        @Override
        public void bleServiceOnReceive(Context context, Intent intent) {

        }

        @Override
        public void bleLeScanDevice(BluetoothDevice bluetoothDevice, int rssi, byte[] scanRecord, BleParams.ScanDeviceStateCode scanDeviceStateCode) {
            switch (scanDeviceStateCode) {
                case START_SCAN:
                    if (scanDeviceStateCode != bleUtil.scanDeviceStateCode) {
                        myHandler.sendMessage(Message.obtain(myHandler, 2, null));
                        bleUtil.scanDeviceStateCode = scanDeviceStateCode;
                    }
                    break;
                case SCAN_ING:
                    myHandler.sendMessage(Message.obtain(myHandler, 0, new DeviceBean(false, bluetoothDevice, rssi, scanRecord)));
                    if (scanDeviceStateCode != bleUtil.scanDeviceStateCode) {
                        myHandler.sendMessage(Message.obtain(myHandler, 1, null));
                        bleUtil.scanDeviceStateCode = scanDeviceStateCode;
                    }
                    break;
            }
        }

        @Override
        public void bleOnGattCallbackConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            LogUtils.i("00000000000000000000");
            myHandler.sendMessage(Message.obtain(myHandler, 3, 0, 0));
            LogUtils.i("111111111111111111");
            switch (status) {
                case BluetoothGatt.GATT_SUCCESS:
                    switch (newState) {
                        case BluetoothProfile.STATE_CONNECTED:
                            myHandler.sendMessage(Message.obtain(myHandler, 3, 1, 0));
                            break;
                        case BluetoothProfile.STATE_DISCONNECTED:
                            myHandler.sendMessage(Message.obtain(myHandler, 3, 1, 1));
                            break;
                        default:
                            myHandler.sendMessage(Message.obtain(myHandler, 3, 1, 2));
                            break;
                    }
                    break;
                default:
                    myHandler.sendMessage(Message.obtain(myHandler, 3, 2, 0));
                    break;
            }
        }

        @Override
        public void bleOnGattCallbackServicesDiscovered(BluetoothGatt gatt, int status) {

        }

        @Override
        public void bleOnGattCallbackCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {

        }

        @Override
        public void bleOnGattCallbackCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            if (characteristic.getUuid().toString().equalsIgnoreCase(BleParams.StrUUID.VERSION_NAME_UUID)) {
                LogUtils.i("111111111111111111111");
            }
            if (characteristic.getUuid().toString().equalsIgnoreCase(BleParams.StrUUID.BATTERY_LEVEL_UUID)) {
            }
        }

        @Override
        public void bleOnGattCallbackCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            LogUtils.i("000000000000000000000");
            LogUtils.a("OnGattCallbackCharacteristicWrite  " + status);
        }
    };


    private MyHandler myHandler = new MyHandler(IndexActivity.this);

    private static class MyHandler extends HandleUtils<IndexActivity> {
        MyHandler(IndexActivity rootT) {
            super(rootT);
        }

        @Override
        public void handler0Event(final IndexActivity object, final Message msg) {
            super.handler0Event(object, msg);
            DeviceBean deviceBean = (DeviceBean) msg.obj;
            if (deviceBean.getDevice().getName() == null) return;
            if (deviceBean.getDevice().getAddress() == null) return;
            for (int i = 0, j = object.bluetoothDeviceList.size(); i < j; i++) {
                DeviceBean hasDeviceBean = object.bluetoothDeviceList.get(i);
                if (deviceBean.getDevice().getName().equals(hasDeviceBean.getDevice().getName())) {
                    return;
                }
            }
            object.deviceListAdapter.addData(deviceBean);
        }


        @Override
        public void handler1Event(IndexActivity object, Message msg) {
            super.handler1Event(object, msg);
            object.btnSearch.setText("Searching......");
        }

        @Override
        public void handler2Event(IndexActivity object, Message msg) {
            super.handler1Event(object, msg);
            object.btnSearch.setText("Search");
        }

        @Override
        public void handler3Event(IndexActivity object, Message msg) {
            super.handler1Event(object, msg);
            if (msg.arg1 == 0) object.progressDialog.hide();
            else if (msg.arg1 == 1 & msg.arg2 == 0) {
                object.tbTitleBar.setTitle("设备:".concat(object.selectedDeviceBean.getDevice().getName()).concat("(点击关闭)"));
                /*Intent intent = new Intent();
                intent.putExtra("DeviceBean", new Gson().toJson(object.selectedDeviceBean));
                intent.setClass(object, CalibrationActivity.class);
                object.startActivity(intent);*/
            } else if (msg.arg1 == 1 && msg.arg2 == 1) {
                object.tbTitleBar.setTitle("设备选择");
                ToastUtils.showShort("连接已断开......");
            } else if (msg.arg1 == 1 && msg.arg2 == 2) {
                object.tbTitleBar.setTitle("设备选择");
                ToastUtils.showShort("连接已断开......");
            } else if (msg.arg1 == 2) {
                object.tbTitleBar.setTitle("设备选择");
                ToastUtils.showShort("连接已断开......");
            }
        }

        @Override
        public void handler4Event(IndexActivity object, Message msg) {
            super.handler4Event(object, msg);
            object.tbTitleBar.setTitle("设备选择");
        }
    }
}
